package dry.example.service.impl;

import dry.example.route.CustomInvocationHandler;
import dry.example.route.RouteAdmin;
import dry.example.service.RouteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author zc
 */
@Service
public class RouteServiceImpl implements RouteService {

    @Autowired
    private RequestMappingHandlerMapping requestMappingHandlerMapping;

    /**
     * 执行
     */
    @Override
    public void run(Object handler) {
        try {
            RequestMappingInfo requestMappingInfo = RequestMappingInfo.paths("testing").methods(RequestMethod.GET).build();


            Method method = findMethod(handler,"h01");

            //Method method = handler.getClass().getMethod("h01");
            requestMappingHandlerMapping.registerMapping(requestMappingInfo, handler, method);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //run02(handler);
    }

    private Method findMethod(Object handler, String methodName) {
        Class<?> handlerClass = handler.getClass();

        for (Method method : handlerClass.getDeclaredMethods()) {
            if (method.getName().equals(methodName)) {
                return method;
            }
        }
        return null;

    }

    public static void run02(Object handler) {
        RouteAdmin demo = (RouteAdmin) Proxy.newProxyInstance(
                RouteAdmin.class.getClassLoader(),
                new Class<?>[]{RouteAdmin.class},
                new CustomInvocationHandler(handler)
        );
    }

}
